package com.xq.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.common.base.Strings;
import com.google.gson.GsonBuilder;
import com.jfinal.core.Controller;
import com.jfinal.log.Logger;
import com.xq.common.Constants;
import com.xq.controller.XQHttpClinet.Request;
import com.xq.controller.XQHttpClinet.Result;
import com.xq.model.XiaoQu;

public class XiaoQuController extends Controller {

	private static Logger logger = Logger.getLogger(ShopController.class);
	private final static String XIAOQU_GEO_TABLE_ID_IN_BAIDU_CLOUD = "67941";
	
	public void nearby() {
		String location = getPara("location");
		String page = this.getPara("page");
		String pageSize = this.getPara("pageSize");
		Request request = new Request();
		request.setUrl(Constants.URL_BAIDU_CLOUD_POI_NEARBY)
				.addPara("geotable_id", XIAOQU_GEO_TABLE_ID_IN_BAIDU_CLOUD)
				.addPara("ak", Constants.BAIDU_CLOUDE_ACCESS_KEY)
				.addPara("location", location)
				.addPara("coord_type", String.valueOf(3))
				.addPara("radius", String.valueOf(2000))
				.addPara("sortby", "distance:-1")
				.addPara("page_index", Strings.isNullOrEmpty(page)? "0": page)
				.addPara("page_size", Strings.isNullOrEmpty(page)? "10": pageSize);
		XQHttpClinet client = new XQHttpClinet();
		Result<String> result = client.execute(request);
	
		if (isSuccess(result))
		{
			List<Long> lbsIdList = new ArrayList<Long>();
			Map<Long, Number> distanceMap = new HashMap<Long, Number>();
			Map map = new GsonBuilder().create().fromJson(result.getData(), Map.class);
			int size = ((Double)map.get("size")).intValue();
			int total =  ((Double)map.get("total")).intValue();
			if (size > 0)
			{
				List content = (List)map.get("contents");
				for(Object object: content)
				{
					Map poi = (Map)object;
					long id = ((Double)poi.get("uid")).longValue();
					int distance = ((Double)poi.get("distance")).intValue();
					lbsIdList.add(id);
					distanceMap.put(id, distance);
				}
			}
			
			List<XiaoQu> xiaoQuList = XiaoQu.dao.findByLBSIdList(lbsIdList);
			
			Map<String, Object> responseObj = new HashMap<String, Object>();
			List<Object> shopMapList = new ArrayList<Object>();
			for(XiaoQu xiaoqu: xiaoQuList)
			{
				long lbsId = xiaoqu.getLong("lbsId");
				Map shopAttrs = xiaoqu.cloneAttrs();
				shopAttrs.put("distance", distanceMap.get(lbsId));
				shopMapList.add(shopAttrs);
			}
			responseObj.put("total", total);
			responseObj.put("size", shopMapList.size());
			responseObj.put("'", shopMapList);
			XQResponse response = new XQResponse(XQResponse.STATUS_SUCCESS
					, "success", new GsonBuilder()
			//.registerTypeAdapter(Integer.class, new GsonNumberToStringAdaptor())
			//.registerTypeAdapter(Long.class, new GsonNumberToStringAdaptor())
			.create()
			.toJson(responseObj));
			renderJson(response);
		} else {
			renderJson(new XQResponse(XQResponse.STATUS_EXCEPTION));
		}
	}

	public void create() {

		String name = getPara("name");
		String address = getPara("address");
		String longitude = getPara("location").split(",")[0].trim();
		String latitude = getPara("location").split(",")[1].trim();

		Request request = new Request();
		request.setUrl(Constants.URL_BAIDU_CLOUD_POI_CREATE)
				.setMethod(XQHttpClinet.METHOD_POST)
				.addPara("geotable_id", XIAOQU_GEO_TABLE_ID_IN_BAIDU_CLOUD)
				.addPara("ak", Constants.BAIDU_CLOUDE_ACCESS_KEY)
				.addPara("longitude", longitude)
				.addPara("latitude", latitude)
				.addPara("coord_type", String.valueOf(3))
				.addPara("title", name)
				.addPara("address", address)
				.addPara("name", name); // 扩展字段，小区名字
		XQHttpClinet client = new XQHttpClinet();
		Result<String> result = client.execute(request);
		String lbsId = "0";
		if (isSuccess(result)) {
			Map map = new GsonBuilder().create().fromJson(result.getData(),
					Map.class);
			lbsId = ((Double) map.get("id")).intValue() + "";
			logger.debug(name + "(" + longitude + ", " + latitude
					+ ") is added to baidu lbs and id is " + lbsId);
		} else {
			renderJson(new XQResponse(XQResponse.STATUS_ADD_SHOP_TO_LBS_FAILED));
			return;
		}
		XiaoQu xiaoqu = new XiaoQu();
		xiaoqu.set("name", name);
		xiaoqu.set("address", address);
		xiaoqu.set("longitude", Double.valueOf(longitude));
		xiaoqu.set("latitude", Double.valueOf(latitude));
		xiaoqu.set("lbsId", Long.valueOf(lbsId));
		xiaoqu.save();
		renderJson(new XQResponse(XQResponse.STATUS_SUCCESS, "success", ""));
	}
	
	private boolean isSuccess(Result<String> result) {
		if (result.getHttpException() != null
				|| result.getResponseParserException() != null) {
			return false;
		}
		if (result.getHttpStatus() > 300) {
			return false;
		}
		String response = result.getData();
		Map map = new GsonBuilder().create().fromJson(response, Map.class);
		if (((Double) map.get("status")).intValue() != 0) {
			return false;
		}
		return true;
	}
}
